var async = require("async")

module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
    DBRemote.channelService = this.app.get('channelService')
    if(DBRemote.dbService && DBRemote.dbService.db){
    	DBRemote.db = DBRemote.dbService.db
    }
}
var maxCheckpoint = 7
var local = {}
//获取闯关信息
DBRemote.prototype.getCheckpointInfo = function(uid,cb) {
	var info = {
		allSuccessNumber : 0,
		playCount : 0,
		winCount : 0,
		allBonus : 0,
		score : 0,
		maxCheckpoint : maxCheckpoint,
		robotCounts : {},
		checkpointRed : 0,
		curTime : (new Date()).getTime()
	}
	async.waterfall([
		function(next) {
			//获取今日总奖金
			DBRemote.dbService.db.get("game:award:checkpoint:allBonus",function(err,data) {
				if(err || !data){
					info.allBonus = 0
				}else{
					info.allBonus = data
				}
				next()
			})
		},
		function(next) {
			//获取总完成人数
			DBRemote.dbService.db.get("game:checkpoint:allSuccessNumber",function(err,data) {
				if(err || !data){
					info.allSuccessNumber = 0
				}else{
					info.allSuccessNumber = data
				}
				next()
			})
		},
		function(next) {
			//获取机器人数量
			DBRemote.dbService.db.hgetall("game:hunanRunQuickly:checkpointRobots",function(err,data) {
				if(err || !data){
					info.allSuccessNumber = {}
				}else{
					info.robotCounts = data
				}
				next()
			})
		},
		function(next) {
			DBRemote.dbService.db.hget("game:checkpoint:score",uid,function(err,data) {
				if(err || !data){
					data = 0
				}
				info.score = data
				next()
			})
		},
		function(next) {
			//获取参与次数
			DBRemote.dbService.db.hget("game:checkpoint:playCount",uid,function(err,data) {
				if(err || !data){
					info.playCount = 0
				}else{
					info.playCount = data
				}
				next()
			})
		},
		function(next) {
			//获取闯关红包
			DBRemote.dbService.db.hget("game:checkpoint:checkpointRed",uid,function(err,data) {
				if(err || !data){
					info.checkpointRed = 0
				}else{
					info.checkpointRed = data
				}
				next()
			})
		},
		function(next) {
			//获取闯关进度
			DBRemote.dbService.db.hget("game:checkpoint:winCount",uid,function(err,data) {
				if(err || !data){
					info.winCount = 0
				}else{
					info.winCount = data
				}
				cb(true,info)
			})
		}
	],function(err) {
		console.log(err)
	})
}
//获取闯关游戏历史记录
DBRemote.prototype.getCheckpointHistory = function(dayStr,cb) {
	var info = {
		allBonus : 0,
		oneBonus : 0,
		allPlayer : 0
	}
	DBRemote.dbService.db.hmget("game:checkpoint:history:"+dayStr,["allBonus","oneBonus","allPlayer"],function(err,data) {
		if(!err && data){
			info.allBonus = data[0]
			info.oneBonus = data[1]
			info.allPlayer = data[2]
		}
		cb(true,info)
	})
}
//获取闯关积分排行榜
DBRemote.prototype.getCheckpointRanking = function(cb) {
	var info = {
		robotInfos : {},
		playerInfos : []
	}
	async.waterfall([
		function(next) {
			//获取机器人信息
			DBRemote.dbService.db.hgetall("game:hunanRunQuickly:checkpointRobotsInfo",function(err,data) {
				if(err || !data){
					info.robotInfos = {}
				}else{
					info.robotInfos = data
				}
				next()
			})
		},
		function() {
			//获取机器人信息
			DBRemote.dbService.db.zrange("game:checkpoint:winscore",-20,-1,"WITHSCORES",function(err,data) {
				if(err){
					cb(true,info)
				}else{
					info.playerInfos = data
					cb(true,info)
				}
			})
		}
	],function(err) {
		console.log(err)
	})
}
//闯关失败
DBRemote.prototype.checkpointLose = function(uid,cb) {
	DBRemote.app.rpc.db.task.updateTask(null,uid,"checkpointPass",0,null)
	console.log("checkpointLose : "+uid)
	DBRemote.dbService.db.hincrby("game:checkpoint:playCount",uid,-1,function(err,data) {
		//闯关信息传到后台
	    var messageInfo = {
	      messageType : "checkpointLose",
	      uid : uid,
	      time : (new Date()).getTime()
	    }
	    DBRemote.dbService.writeMessage(JSON.stringify(messageInfo))
		cb(true)
	})
}
//闯关成功
DBRemote.prototype.checkpointWin = function(uid,score,cb) {
	// console.log("checkpointWin : "+uid+score)
	DBRemote.dbService.db.hincrby("game:checkpoint:score",uid,score,function(){
		DBRemote.dbService.db.hincrby("game:checkpoint:winCount",uid,1,function(err,data) {
			if(!err && data){
				//闯关信息传到后台
			    var messageInfo = {
			      messageType : "checkpointWin",
			      uid : uid,
			      score : score,
			      checkpoint : data,
			      time : (new Date()).getTime()
			    }
			    DBRemote.dbService.writeMessage(JSON.stringify(messageInfo))
			    DBRemote.app.rpc.db.task.updateTask(null,uid,"checkpointPass",data,null)
				if(data == maxCheckpoint){
					local.checkpointSuccess(uid)
				}
			}
			cb(true)
		})
	})
}
//领取关卡红包
DBRemote.prototype.getCheckpointRed = function(uid,checkpoint,cb) {
	var curCheckpoint = 0
	var checkpointRed = 0
	checkpoint = parseInt(checkpoint)
	async.waterfall([
			function(next) {
				DBRemote.dbService.db.hget("game:checkpoint:winCount",uid,function(err,data) {
					if(!err && data){
						curCheckpoint = parseInt(data)
					}
					if(checkpoint > curCheckpoint){
						cb(false,"未通关")
					}else{
						next()
					}
				})
			},
			function(next) {
				DBRemote.dbService.db.hget("game:checkpoint:checkpointRed",uid,function(err,data) {
					if(!err && data){
						checkpointRed = parseInt(data)
					}else{
						checkpointRed = 0
					}
					var tmpNum = Math.pow(2,checkpoint - 1)
					if(!(checkpointRed & tmpNum)){
						DBRemote.dbService.db.hincrby("game:checkpoint:checkpointRed",uid,tmpNum,function(err,data) {
							if(!err){
								next()
							}else{
								console.log(err)
								cb(false)
							}
						})
					}else{
						cb(false,"已领取")
					}
				})
			},
			function() {
				DBRemote.dbService.db.hget("game:checkpoint:awardInfo",checkpoint,function(err,data) {
					var value = 1
					var itemId= 101
					if(!err && data){
						data = JSON.parse(data)
						if(data.itemId == 103){
							value = Math.random() * (data.maxValue - data.minValue) + data.minValue
							value = parseFloat(value.toFixed(2))
						}else{
							value = parseInt(Math.random() * (data.maxValue - data.minValue) + data.minValue)
						}
						itemId = parseInt(data.itemId)
					}else{
						console.log(err,data)
					}
					var shareAward = {
						checkpoint : checkpoint,
						itemId : itemId,
						value : value
					}
					DBRemote.dbService.db.hset("game:checkpoint:shareAward",uid,JSON.stringify(shareAward))
					DBRemote.dbService.addItemReason(uid,itemId,value,"闯关:"+checkpoint,function(flag) {
						cb(true,{itemId : itemId,value : value})
					})
				})
			}
		],
		function(err) {
			console.log(err)
		})
}
//领取分享关卡红包
DBRemote.prototype.getShareCheckpointRed = function(uid,checkpoint,itemId,value,isApp,cb) {
	DBRemote.dbService.db.hget("game:checkpoint:shareAward",uid,function(err,data) {
		if(err || !data){
			cb(false)
			return
		}
		var shareAward = JSON.parse(data)
		if(shareAward.checkpoint != checkpoint || shareAward.itemId != itemId || shareAward.value != value){
			cb(false,"参数错误")
			return
		}
		DBRemote.dbService.db.hdel("game:checkpoint:shareAward",uid,function(err,data) {
			if(!err && data){
				if(isApp){
					DBRemote.dbService.addItemReason(uid,shareAward.itemId,shareAward.value,"闯关翻倍:"+shareAward.checkpoint,function(flag) {
						cb(true,shareAward)
					})
				}else{
					shareAward.value = 0
					cb(true,shareAward)
				}
			}else{
				cb(false,"已领取")
			}
		})
	})
}
//成功闯过最终关
local.checkpointSuccess = function(uid) {
	DBRemote.dbService.db.hincrby("game:checkpoint:success",uid,1)
	DBRemote.dbService.db.hget("game:checkpoint:score",uid,function(err,data){
		if(!err){
			var score = parseInt(data)
			DBRemote.dbService.db.hgetall("nn:acc:"+uid,function(err,data) {
				if(!err && data){
					var obj = {
						uid : uid,
						head : data.head,
						nickname : data.nickname
					}
					DBRemote.dbService.db.zadd("game:checkpoint:winscore",score,JSON.stringify(obj),function(){})
				}
			})
		}
		//通知
		var notify = {
			"cmd" : "checkpointSuccess",
			"score" : data
		}
		DBRemote.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
		local.broadcastCheckpointSuccess(uid)
	})
	DBRemote.dbService.db.incrby("game:checkpoint:allSuccessNumber",1)
}
//广播闯关通关信息
local.broadcastCheckpointSuccess = function(uid) {
	// console.log("广播闯关通关信息",uid)
	DBRemote.dbService.getPlayerString(uid,"nickname",function(data) {
		// console.log("data",data)
		if(data){
			DBRemote.channelService.broadcast("connector","onNotify",{"type":"checkpointSuccess","data":data})
		}
	})
}

//获取战绩
DBRemote.prototype.getHistory = function(uid,cb) {
	DBRemote.dbService.db.lrange("game:run:history:"+uid,0,-1,function(err,data) {
		if(!err){
			cb(true,data)
		}else{
			console.log(err)
			cb(true,[])
		}
	})
}

//保存房间战绩
DBRemote.prototype.saveRoomHistory = function(roomInfo,cb) {
	roomInfo.time = (new Date()).getTime()
	for(var i in roomInfo.players){
		local.savePlayerHistory(roomInfo.players[i].uid,JSON.stringify(roomInfo))
	}
	//战绩传到后台
    var messageInfo = {
      messageType : "historyRecord",
      roomInfo : roomInfo,
      time : (new Date()).getTime()
    }
    DBRemote.dbService.writeMessage(JSON.stringify(messageInfo))
	cb()
}
local.savePlayerHistory = function(uid,history) {
	DBRemote.dbService.db.lpush("game:run:history:"+uid,history,function(err) {
		if(!err){
			DBRemote.dbService.db.ltrim("game:run:history:"+uid,0,10)
		}
	})
}
/**
 * [保存金币数据]
 * @Author   wfd
 * @DateTime 2018-06-12
 * @param    {[type]}   obj [{uid : uid,score : score}]
 * @param    {[type]}   win [description]
 * @param    {Function} cb  [description]
 * @return   {[type]}       [description]
 */
DBRemote.prototype.saveGoldData = function(obj,win,cb) {
	for(var i = 0;i < obj.length;i++){
		if(obj[i].uid > 10000){
			DBRemote.app.rpc.db.task.updateTask(null,obj[i].uid,"goldplay",1,null)
			DBRemote.dbService.incrbyPlayer(obj[i].uid,"allGame",1,function(){})
			if(obj[i].uid == win){
				local.savePlayerGoldWin(obj[i].uid)
			}else{
				DBRemote.dbService.setPlayer(obj[i].uid,"curWin",0,function(){})
			}
			local.savePlayerGoldScore(obj[i].uid,obj[i].score)
		}
	}
	cb()
}

local.savePlayerGoldWin = function(uid) {
	DBRemote.dbService.incrbyPlayer(uid,"allWin",1,function(){})
	DBRemote.app.rpc.db.task.updateTask(null,uid,"goldwin",1,null)
	DBRemote.dbService.incrbyPlayer(uid,"curWin",1,function(flag,curValue){
		if(flag){
			DBRemote.app.rpc.db.task.updateTask(null,uid,"goldstreak",curValue,null)
			DBRemote.dbService.getPlayer(uid,"maxWin",function(value) {
				if(value !== false){
					if(curValue > value){
						DBRemote.dbService.incrbyPlayer(uid,"maxWin",1,function(){})
					}
				}
			})
		}
	})
}
local.savePlayerGoldScore = function(uid,score) {
	DBRemote.dbService.getPlayer(uid,"maxScore",function(value) {
		if(value !== false){
			if(score > value){
				DBRemote.dbService.setPlayer(uid,"maxScore",score,function(){})
			}
		}
	})
}